package com.heima.crm.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.crm.annotation.MyLog;
import com.heima.crm.common.contents.CommonMessageContent;
import com.heima.crm.common.contents.HoldingConstant;
import com.heima.crm.common.result.PageResult;
import com.heima.crm.common.result.Result;
import com.heima.crm.common.utils.BaseContext;
import com.heima.crm.exception.BaseException;
import com.heima.crm.mapper.*;
import com.heima.crm.pojos.dtos.*;
import com.heima.crm.pojos.entity.*;
import com.heima.crm.pojos.vos.BusinessDetailVo;
import com.heima.crm.pojos.vos.BusinessPageVo;
import com.heima.crm.pojos.vos.HistoryFollowVo;
import com.heima.crm.service.TbBusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-07-15
 */
@Service
@Slf4j
@Transactional
public class TbBusinessServiceImpl extends ServiceImpl<TbBusinessMapper, TbBusiness> implements TbBusinessService {

    @Autowired
    private TbBusinessMapper tbBusinessMapper;
    @Autowired
    private TbCustomerMapper tbCustomerMapper;
    @Autowired
    private CrUserMapper crUserMapper;
    @Autowired
    private TbBusinessFollowMapper tbBusinessFollowMapper;
    @Autowired
    private TransferMapper transferMapper;

    @Override
    @MyLog
    public Result<PageResult<BusinessPageVo>> findAllBusiness(BusinessPageDto dto) {

        if (dto == null) {
            throw new BaseException(CommonMessageContent.INVALID_PARAMETER);
        }

        if (dto.getPage() == null) {
            dto.setPage(1);
        }

        if (dto.getSize() == null || dto.getSize() > 10) {
            dto.setSize(10);
        }

        List<BusinessPageVo> pageVos = new ArrayList<>();

        IPage<TbBusiness> page = null;

        TbUser tbUser = crUserMapper.selectById(BaseContext.getCurrentId());
        if (dto.getType() == 0) {
            //商机分页查询
            //构建复杂查询对象
            LambdaQueryWrapper<TbBusiness> lqw = buildQuery(dto, tbUser);

            if (dto.getStatus() != null) {
                lqw.eq(TbBusiness::getStatus, dto.getStatus());
            } else {
                lqw.in(TbBusiness::getStatus, 0, 1);
            }

            page = new Page<>(dto.getPage(), dto.getSize());

            page(page, lqw);

            List<TbBusiness> records = page.getRecords();

            for (TbBusiness record : records) {
                BusinessPageVo businessPageVo = new BusinessPageVo();

                BeanUtils.copyProperties(record, businessPageVo);
                pageVos.add(businessPageVo);
            }

        } else if (dto.getType() == 1) {

            LambdaQueryWrapper<TbBusiness> lqw = buildQuery(dto, tbUser);

            if (dto.getStatus() != null) {
                lqw.eq(TbBusiness::getStatus, dto.getStatus());
            } else {
                lqw.in(TbBusiness::getStatus, 2);
            }

            page = new Page<>(dto.getPage(), dto.getSize());

            page(page, lqw);

            List<TbBusiness> records = page.getRecords();

            for (TbBusiness record : records) {
                BusinessPageVo businessPageVo = new BusinessPageVo();

                BeanUtils.copyProperties(record, businessPageVo);
                pageVos.add(businessPageVo);
            }
        }

        PageResult<BusinessPageVo> pageResult = new PageResult<>();
        pageResult.setRecords(pageVos);
        pageResult.setTotal(page.getTotal());

        log.info(JSON.toJSONString(pageResult));

        return Result.success(pageResult);
    }

    /**
     * 新增商机
     *
     * @param dto
     * @return
     */
    @Override
    public Result addBusiness(BusinessAddDto dto) {

        //参数校验
        if (dto == null) {
            throw new BaseException(CommonMessageContent.INVALID_PARAMETER);
        }
        //保存用户表
        TbCustomer tbCustomer = new TbCustomer();
        BeanUtils.copyProperties(dto, tbCustomer);
        tbCustomer.setDealStatus((short) 0);
        tbCustomerMapper.insert(tbCustomer);

        //新增商机表
        TbBusiness tbBusiness = new TbBusiness();
        Long currentId = BaseContext.getCurrentId();

        TbUser tbUser = crUserMapper.selectById(currentId);

        if (tbUser == null) {
            throw new BaseException("登陆后重试");
        }

//        tbBusiness.setAscriptionId(tbUser.getUserId());
//        tbBusiness.setAscriptionName(tbUser.getUserName());
        tbBusiness.setDisciplineId(dto.getDisciplineId());
        tbBusiness.setPhone(dto.getPhone());
        tbBusiness.setStatus((short) 2);
        tbBusiness.setCreateTime(LocalDateTime.now());
        tbBusiness.setCustomerId(tbCustomer.getId());
        tbBusiness.setCustomerName(tbCustomer.getCustomerName());

        tbBusinessMapper.insert(tbBusiness);

        return Result.success();
    }

    /**
     * 回显该商机所有跟进记录
     *
     * @param businessId
     * @return
     */
    @Override
    public Result findCustomerCondition(Long businessId) {

        TbBusiness tbBusiness = tbBusinessMapper.selectById(businessId);

        TbCustomer tbCustomer = tbCustomerMapper.selectById(tbBusiness.getCustomerId());

        if (tbCustomer == null) {
            throw new BaseException(CommonMessageContent.INVALID_PARAMETER);
        }
        List<TbBusinessFollow> businessFollows = tbBusinessFollowMapper.selectList(Wrappers.<TbBusinessFollow>lambdaQuery().eq(TbBusinessFollow::getBusinessId, businessId)
                .eq(TbBusinessFollow::getCustomerId, tbCustomer.getId()));

        List<HistoryFollowVo> historyFollowVos = new ArrayList<>();

        System.out.println(JSON.toJSONString(businessFollows));

        if (businessFollows != null && businessFollows.size() > 0) {
            for (TbBusinessFollow businessFollow : businessFollows) {
                HistoryFollowVo historyFollowVo = new HistoryFollowVo();

                historyFollowVo.setFocus(businessFollow.getFocus());
                historyFollowVo.setSummary(businessFollow.getSummary());
                historyFollowVo.setUsername(businessFollow.getUsername());
                historyFollowVo.setUserId(businessFollow.getUserId());
                historyFollowVo.setStatus(businessFollow.getStatus() + "下次跟进时间" + businessFollow.getNextFollowTime().toString());
                historyFollowVo.setNextFollowTime(businessFollow.getNextFollowTime());

                historyFollowVos.add(historyFollowVo);
            }
        }

        return Result.success(historyFollowVos);
    }

    /**
     * 分配商机
     *
     * @param
     * @return
     */
    @Override
    public Result assignBusiness(BusinessAssignDto dto) {

        if (dto == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
        Long[] ids = dto.getIds();

        TbTransfer tbTransfer = transferMapper.selectOne(Wrappers.<TbTransfer>lambdaQuery().eq(TbTransfer::getUserId, BaseContext.getCurrentId()));

        if (tbTransfer.getBusyNum() + ids.length > HoldingConstant.HOLDING_COUNT) {
            return Result.error("保有量已达上线,对多可分配" + (HoldingConstant.HOLDING_COUNT - tbTransfer.getBusyNum()) + "条");
        }

        if (dto.getUserId() != null) {
            TbUser tbUser = crUserMapper.selectById(dto.getUserId());
            //根据id查询所有商机
            List<TbBusiness> tbBusinesses = tbBusinessMapper.selectBatchIds(Arrays.asList(ids));

            for (TbBusiness tbBusiness : tbBusinesses) {
                tbBusiness.setAscriptionId(tbUser.getUserId());
                tbBusiness.setAscriptionName(tbUser.getUserName());
                tbBusiness.setStatus((short) 0);
                tbBusinessMapper.updateById(tbBusiness);
                tbTransfer.setBusyNum(tbTransfer.getBusyNum() + ids.length);
                tbTransfer.setUpdateTime(LocalDateTime.now());
                tbTransfer.setUpdateId(BaseContext.getCurrentId());
                transferMapper.updateById(tbTransfer);
            }
        }

        return Result.success();
    }

    /**
     * 回显该商机的详细数据
     *
     * @param businessId
     * @return
     */
    @Override
    public Result findBusinessDetail(Long businessId) {
        //参数校验
        TbBusiness tbBusiness = tbBusinessMapper.selectById(businessId);
        if (tbBusiness == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }

        TbCustomer tbCustomer = tbCustomerMapper.selectById(tbBusiness.getCustomerId());
        if (tbCustomer == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }

        BusinessDetailVo businessDetailVo = new BusinessDetailVo();
        BeanUtils.copyProperties(tbCustomer, businessDetailVo);

        List<TbBusinessFollow> tbBusinessFollows = tbBusinessFollowMapper.selectList(Wrappers.<TbBusinessFollow>lambdaQuery().eq(TbBusinessFollow::getBusinessId, businessId).orderByDesc(TbBusinessFollow::getCreateTime));
        //只回显最新的数据
        if (tbBusinessFollows != null && tbBusinessFollows.size() > 0) {
            TbBusinessFollow tbBusinessFollow = tbBusinessFollows.get(0);

            businessDetailVo.setCourse(tbBusinessFollow.getCourse());
            businessDetailVo.setCareerPlans(tbBusinessFollow.getCareerPlans());
            businessDetailVo.setTimePlans(tbBusinessFollow.getTimePlans());
            businessDetailVo.setLearningReason(tbBusinessFollow.getLearningReason());
            businessDetailVo.setOtherPlans(tbBusinessFollow.getOtherPlans());
        }

        return Result.success(businessDetailVo);
    }

    /**
     * 跟进商机
     *
     * @param dto
     * @return
     */
    @Override
    public Result followBusiness(BusinessFollowDto dto) {

        if (dto == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
        Long customerId = dto.getId();
        TbCustomer tbCustomer = tbCustomerMapper.selectById(customerId);
        //更新用户信息
        updateCustomer(dto, tbCustomer);

        //添加跟进记录
        TbBusinessFollow tbBusinessFollow = new TbBusinessFollow();
        BeanUtils.copyProperties(dto, tbBusinessFollow);
        tbBusinessFollow.setId(null);

        Long currentId = BaseContext.getCurrentId();
        TbUser tbUser = crUserMapper.selectById(currentId);

        tbBusinessFollow.setUserId(currentId);
        tbBusinessFollow.setCourseId(dto.getCourseId());
        tbBusinessFollow.setUsername(tbUser.getUserName());
        tbBusinessFollow.setBusinessId(dto.getBusinessId());

        tbBusinessFollowMapper.insert(tbBusinessFollow);

        return Result.success();
    }

    /**
     * 退回公海池
     *
     * @param dto
     * @return
     */
    @Override
    public Result returnBusiness(BusinessReturnDto dto) {

        if (dto == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }

        Long businessId = dto.getBusinessId();

        TbBusiness tbBusiness = tbBusinessMapper.selectById(businessId);
        tbBusiness.setStatus((short) 2);
        tbBusiness.setReturnPoolReason(dto.getReason());
        tbBusiness.setReturnTime(LocalDateTime.now());

        tbBusinessMapper.updateById(tbBusiness);
        //更新转派
        LambdaQueryWrapper<TbTransfer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TbTransfer::getUserId, tbBusiness.getAscriptionId());
        TbTransfer tbTransfer = transferMapper.selectOne(lqw);
        tbTransfer.setBusyNum(tbTransfer.getBusyNum() - 1);
        tbTransfer.setUpdateTime(LocalDateTime.now());
        tbTransfer.setUpdateId(BaseContext.getCurrentId());
        transferMapper.updateById(tbTransfer);

        return Result.success();
    }

    /**
     * 批量捞取
     *
     * @param businessIds
     * @return
     */
    @Override
    public Result scoopBatch(Long[] businessIds) {

        if (businessIds == null || businessIds.length == 0) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }

        Long currentId = BaseContext.getCurrentId();
        TbTransfer tbTransfer = transferMapper.selectOne(Wrappers.<TbTransfer>lambdaQuery().eq(TbTransfer::getUserId, BaseContext.getCurrentId()));

        if (tbTransfer.getBusyNum() + businessIds.length > HoldingConstant.HOLDING_COUNT) {
            return Result.error("保有量已达上线,对多可分配" + (HoldingConstant.HOLDING_COUNT - tbTransfer.getBusyNum()) + "条");
        }
        if (currentId == null) {
            return Result.error(CommonMessageContent.USER_DOES_NOT_EXIST);
        }
        TbUser tbUser = crUserMapper.selectById(currentId);

        for (Long businessId : businessIds) {

            TbBusiness tbBusiness = tbBusinessMapper.selectById(businessId);
            tbBusiness.setStatus((short) 0);
            tbBusiness.setAscriptionId(currentId);
            tbBusiness.setAscriptionName(tbUser.getUserName());

            tbBusinessMapper.updateById(tbBusiness);

        }
        //更新转派


        tbTransfer.setBusyNum(tbTransfer.getBusyNum() + businessIds.length);
        tbTransfer.setUpdateId(BaseContext.getCurrentId());
        tbTransfer.setUpdateTime(LocalDateTime.now());
        transferMapper.updateById(tbTransfer);
        return Result.success();
    }

    /**
     * 更新用户
     *
     * @param dto
     * @param tbCustomer
     */
    private void updateCustomer(BusinessFollowDto dto, TbCustomer tbCustomer) {

//        if (dto.getCustomerName()!=null&&!"".equals(dto.getCustomerName())){
//            tbCustomer.setCustomerName(dto.getCustomerName());
//        }
//
//        if (dto.getPhone()!=null&&!"".equals(dto.getPhone())){
//            tbCustomer.setPhone(dto.getPhone());
//        }
//
//        if (dto.getJob()!=null&&!"".equals(dto.getJob())){
//            tbCustomer.setJob(dto.getJob());
//        }
//        if (dto.getDegree()!=null&&!"".equals(dto.getDegree())){
//            tbCustomer.setDegree(dto.getDegree());
//        }
//        if (dto.getWechat()!=null&&!"".equals(dto.getWechat())){
//            tbCustomer.setWechat(dto.getWechat());
//        }
//        if (dto.getArea()!=null&&!"".equals(dto.getArea())){
//            tbCustomer.setArea(dto.getArea());
//        }

        TbCustomer tbCustomer1 = new TbCustomer();
        BeanUtils.copyProperties(dto, tbCustomer1);

        tbCustomerMapper.updateById(tbCustomer1);
    }

    /**
     * 构建复杂查询对象
     *
     * @param dto
     * @return
     */
    private LambdaQueryWrapper<TbBusiness> buildQuery(BusinessPageDto dto, TbUser tbUser) {

        LambdaQueryWrapper<TbBusiness> lqw = new LambdaQueryWrapper<>();

        if (dto.getCustomerId() != null) {
            lqw.eq(TbBusiness::getCustomerId, dto.getCustomerId());
        }

        if (dto.getPhone() != null && !"".equals(dto.getPhone())) {
            lqw.like(TbBusiness::getPhone, dto.getPhone());
        }

        if (dto.getCustomerName() != null && !"".equals(dto.getCustomerName())) {
            lqw.like(TbBusiness::getCustomerName, dto.getCustomerName());
        }

        String ascriptionName = dto.getAscriptionName();
        if (ascriptionName != null && !"".equals(ascriptionName)) {
            if (ascriptionName.equals(CommonMessageContent.MY_BUSINESS)) {
                lqw.eq(TbBusiness::getAscriptionId, tbUser.getUserId());
            }
        }

        if (dto.getBeginTime() != null && dto.getEndTime() != null&&!"".equals(dto.getBeginTime())&&!"".equals(dto.getEndTime())) {

            lqw.between(TbBusiness::getCreateTime, dto.getBeginTime(), dto.getEndTime());
        }

        return lqw;
    }
}
